package com.xiaoyun.controller.center;

import com.xiaoyun.bo.center.CenterUserBO;
import com.xiaoyun.controller.BaseController;
import com.xiaoyun.pojo.Users;
import com.xiaoyun.resource.FileUpload;
import com.xiaoyun.service.center.CenterUserService;
import com.xiaoyun.utils.*;
import com.xiaoyun.vo.UsersVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

@Api("用户信息接口")
@RestController
@RequestMapping("userInfo")
@RequiredArgsConstructor
public class CenterUserController extends BaseController {

    private final CenterUserService centerUserService;
    private final FileUpload fileUpload;

    @ApiOperation("获取用户信息")
    @PostMapping("update")
    public XYJSONResult update(@RequestParam String userId,
                               @RequestBody @Valid CenterUserBO centerUserBO,
                               HttpServletRequest request,
                               HttpServletResponse response) {
        Users userResult = centerUserService.updateUserInfo(userId, centerUserBO);
        // 增加token
        UsersVO usersVO = conventUsersVO(userResult);
        CookieUtils.setCookie(request, response, "user",
                JsonUtils.objectToJson(usersVO), true);


        return XYJSONResult.ok();
    }

    @ApiOperation("用户头像修改")
    @PostMapping("uploadFace")
    public XYJSONResult uploadFace(@RequestParam String userId,
                                   MultipartFile file,
                                   HttpServletRequest request,
                                   HttpServletResponse response) {
        String fileSpace = System.getProperty("user.dir") + fileUpload.getImageUserFaceLocation();
        String uploadPathPrefix = "/" + userId;
        if (file != null) {
            String filename = file.getOriginalFilename();
            if (StringUtils.isNotBlank(filename)) {
                String[] fileNameArr = filename.split("\\.");
                String suffix = fileNameArr[fileNameArr.length - 1];

                //校验是否为图片格式
                List<String> imgSub = Arrays.asList("png", "jpg", "jpeg");
                if (!imgSub.contains(suffix) || fileNameArr.length < 2) {
                    return XYJSONResult.errorMsg("图片格式不正确");
                }
                String newFileName = "face-" + userId + "." + suffix;
                String finalFacePath = fileSpace + uploadPathPrefix + File.separator + newFileName;
                uploadPathPrefix += ("/" + newFileName);
                File outFile = new File(finalFacePath);
                if (outFile.getParentFile() != null) {
                    outFile.getParentFile().mkdirs();
                }
                try (FileOutputStream fileOutputStream = new FileOutputStream(outFile);
                     InputStream inputStream = file.getInputStream()) {
                    IOUtils.copy(inputStream, fileOutputStream);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {

            return XYJSONResult.errorMsg("文件不能为空");
        }
        String imageServerUrl = fileUpload.getImageServerUrl();
        String finalUserFaceUrl = imageServerUrl + uploadPathPrefix + "?t="
                + DateUtil.getCurrentDateString(DateUtil.DATE_PATTERN);
        Users userResult = centerUserService.updateUserFace(userId, finalUserFaceUrl);

        // 增加token
        UsersVO usersVO = conventUsersVO(userResult);
        CookieUtils.setCookie(request, response, "user",
                JsonUtils.objectToJson(usersVO), true);

        return XYJSONResult.ok(userResult);
    }


}
